<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { informationdisclosureApi as MainApi, informationdisclosureById as MainById } from '@T2/service/api.ts';
import { useCurrentWatchStore } from '@T2/store/users.ts';
import { deepCopy } from '@T2/utils/utils.ts';
import dayjs from 'dayjs';
import UploadAttachment from '@T2/components/uploadAttachment/index.vue';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;

const { type, row, dftData, options } = defineProps({
  type: {
    type: String,
    validator(value) {
      return ['新增', '编辑'].includes(value);
    },
    required: true,
  },
  row: {
    type: [Object, null],
    required: true,
  },
  dftData: {
    type: [Object, null],
    required: true,
  },
  options: {
    type: Array,
    required: true,
  },
});
const emits = defineEmits(['closed']);
const showRf = ref(true);

const nowTime = dayjs();
onMounted(() => {
  if (type === '新增') {
    Rt.form = {
      is_date_active: true,
      show_date: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      files: [],
      ...(dftData || {}),
    };
    Rt.files_json = [];
    Rt.files_updateTimes++;
  } else if (type === '编辑') {
    const { id, title, type, is_date_active, show_date, content, files, files_json } = deepCopy(row);
    Rt.form = { id, title, type, is_date_active, show_date, content, files };
    Rt.files_json = files_json || [];
    Rt.files_updateTimes++;
  }
});

const Rt = reactive({
  form: {},
  files_json: [],
  files_updateTimes: 0,
});
const FormRef = ref(null);
const disabledDate = (time) => {
  return dayjs(time).isBefore(nowTime, 'day');
}
const disabledHours = () => {
  if (!Rt.form.show_date) {
    return [];
  };
  const selectedDay = dayjs(Rt.form.show_date);
  if (selectedDay.isSame(nowTime, 'day')) {
    return Array.from({ length: nowTime.hour() }, (_, i) => i); // 禁用当前小时之前
  }
  return [];
}
const disabledMinutes = (hour) => {
  if (!Rt.form.show_date) {
    return [];
  }
  const selectedDay = dayjs(Rt.form.show_date);
  if (selectedDay.isSame(nowTime, 'day') && hour === nowTime.hour()) {
    return Array.from({ length: nowTime.minute() }, (_, i) => i); // 禁用当前分钟之前
  }
  return [];
}
const disabledSeconds = (hour, minute) => {
  if (!Rt.form.show_date) {
    return [];
  }
  const selectedDay = dayjs(Rt.form.show_date);
  if (
    selectedDay.isSame(nowTime, 'day') &&
    hour === nowTime.hour() &&
    minute === nowTime.minute()
  ) {
    return Array.from({ length: nowTime.second() }, (_, i) => i); // 禁用当前秒之前
  }
  return [];
}
const isDateActiveChange = (value) => {
  if (value && !Rt.form.show_date) {
    Rt.form.show_date = dayjs().format('YYYY-MM-DD HH:mm:ss');
  }
}
const fjChange = (files) => {
  Rt.form.files = files;
}

const handleSubmit = async () => {
  const isValid = await FormRef.value.validate(valid => valid);
  if (!isValid) {
    return;
  }
  if (!Rt.form.is_date_active) {
    Rt.form.show_date = null;
  }
  if (type === '新增') {
    AddMain();
  } else if (type === '编辑') {
    EditMain();
  }
}
const AddMain = () => {
  MainApi({
    method: 'post',
    data: {
      ...Rt.form,
      project: curProject.id,
    }
  }).then(res => {
    ElMessage.success('新增成功');
    handleCancel(true);
  }).catch(res => {
    ElMessage.error('新增失败');
    handleCancel(true);
  });
}
const EditMain = () => {
  MainById({
    method: 'patch',
    id: Rt.form.id,
    data: {
      ...Rt.form,
    }
  }).then(res => {
    ElMessage.success('编辑成功');
    handleCancel(true);
  }).catch(res => {
    ElMessage.error('编辑失败');
    handleCancel(true);
  });
}

const handleCancel = (refresh = false) => {
  emits('closed', refresh);
}
</script>

<template>
  <div>
    <el-drawer v-model="showRf" :title="`${ type }信息公开`" size="980" @closed="handleCancel()">
      <el-form
        ref="FormRef"
        :model="Rt.form"
        label-width="120px"
      >
        <div class="flex flex-wrap">
          <el-form-item prop="title" label="标题：" style="width: 50%;" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
            <el-input v-model="Rt.form.title"></el-input>
          </el-form-item>
          <el-form-item prop="type" label="类型：" style="width: 50%;">
            <el-select v-model="Rt.form.type">
              <el-option :key="item.id" :label="item.name" :value="item.id" v-for="item in options" />
            </el-select>
          </el-form-item>
          <el-form-item prop="is_date_active" label="展示期限：" style="width: 50%;">
            <el-radio-group v-model="Rt.form.is_date_active" @change="isDateActiveChange">
              <el-radio label="关闭" :value="false"></el-radio>
              <el-radio label="开启" :value="true"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="show_date" label="展示截止时间：" style="width: 50%;" v-if="Rt.form.is_date_active">
            <el-date-picker
              v-model="Rt.form.show_date"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择截止时间"
              :disabled-date="disabledDate"
              :disabled-hours="disabledHours"
              :disabled-minutes="disabledMinutes"
              :disabled-seconds="disabledSeconds"
              :clearable="false"
              :teleported="false"
            />
          </el-form-item>
          <el-form-item prop="content" label="内容：" style="width: 100%;" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
            <el-input
              type="textarea"
              style="width: calc(50%*1.9 + 120px*0.05);"
              v-model="Rt.form.content"
              :rows="20"
            />
          </el-form-item>
          <el-form-item style="width: 50%;" prop="files" label="上传附件：">
            <UploadAttachment
              :fj_json="Rt.files_json"
              :updateTimes="Rt.files_updateTimes"
              :maxSizeMB="20"
              @files-change="fjChange"
            >
              <div class="upload_info" style="margin-top: 6px">请上传必要的文件，不超过20MB</div>
            </UploadAttachment>
          </el-form-item>
        </div>
      </el-form>
    
      <template #footer>
        <div style="flex: auto">
          <el-button @click="showRf = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit()">确 定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>

</style>